<?php
$itemid = isset($_POST['itemid'])?$_POST['itemid']:"";
$stock_action = isset($_POST['stock_action'])?$_POST['stock_action']:"";
$details = isset($_POST['details'])?$_POST['details']:"";
$qty = isset($_POST['qty'])?(int)$_POST['qty']:"";

if(isset($_POST['update_item'])){
	if(!empty($itemid) && !empty($qty) && is_numeric($qty)){
		if($stock_action == 'OUT') $qty = (int) $qty*-1;
		if(mysql_query("INSERT INTO `item_logs`(`itemid`,`qty`,`details`,`date`,`action`) VALUES ('".$itemid."',".$qty.",'".$_POST['details']."',NOW(),'".$stock_action."')") &&
		mysql_query("UPDATE `items` SET `stock` = `stock` + ".$qty." WHERE `itemid` = ".$itemid)
		){
			
			echo '<div class="success">Update Success</div>';
		}
		else echo '<div class="failed">Update Failed</div>';
	}
	else echo '<div class="failed">One of the fields is <strong>empty</strong> OR<br>invalid input for <strong>Qty</strong></div>';
}


?>
<form name="form1" method="post" action="">
<table align="center" width="400" border="0">
  <tr>
    <th colspan="2">&nbsp;</td>
  </tr>
  <tr>
    <td><label for="itemid">Item Name</label></td>
    <td><select name="itemid">
    	<?php
		$tmp = mysql_query("SELECT `itemid`,`name` FROM `items`");
		while($row = mysql_fetch_assoc($tmp)){
			echo '<option value="'.$row['itemid'].'" '.($itemid==$row['itemid']?'selected="selected"':'').'>'.$row['name'].'</option>';
		}
        ?>
    	</select>
        </td>
  </tr>
  <tr>
    <td><label for="qty">Qty</label></td>
    <td>
    <input name="qty" type="text" id="qty" size="3" value="<?=isset($_POST['qty'])?$_POST['qty']:""?>">
    <select name="stock_action">
    	<option value="OUT" <?=$stock_action=='OUT'?'selected="selected"':""?>>OUT</option>
    	<option value="IN" <?=$stock_action=='IN'?'selected="selected"':""?>>IN</option>
        
    </select>
    </td>
  </tr>
  <tr>
    <td><label for="details">Details<br /><em>(optional)</em></label></td>
    <td>
      <textarea name="details" id="details" cols="45" rows="5"><?=isset($_POST['details'])?$_POST['details']:""?></textarea>
    </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><button type="submit" name="update_item"><strong>Submit</strong></button></td>
  </tr>
</table>
</form>
